package san.java.day15;

/**
 * 生产者/消费者问题
 */

class Producer {
    public static int productNum = 0;
}

public class Thread_09 {
    public static void main(String[] args) {

        Producer p = new Producer();

        // 生产者
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (p) {
                    while (true) {
                        if (p.productNum == 0) {
                            System.out.println("产品数为0, 开始生产");
                            p.productNum += 4;
                            System.out.println("产品数为: " + p.productNum + "结束生产");
                            p.notify();
                        } else {
                            try {
                                p.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }, "生产者").start();


        // 消费者
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (p) {
                    while (true) {
                        if (p.productNum > 0) {
                            System.out.println("产品数为" + p.productNum + "正在消费");
                            p.productNum--;
                            p.notify();
                        } else {
                            System.out.println("没货了");
                            try {
                                p.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }, "消费者").start();
    }
}
